﻿using System;
using System.Net;
using System.Text.RegularExpressions;
using Mini.Resource;
namespace Mini.Common
{
    public class UrlHelper
    {
        public static bool IsUrlExits(string url)
        {
            if (string.IsNullOrEmpty(url))
                return false;
            try
            {
                HttpWebResponse response = null;
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "HEAD";
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    return response.StatusCode == HttpStatusCode.OK;
                }
                catch (WebException ex)
                {
                    return false;
                }
                finally
                {
                    // Don't forget to close your response.
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }

        }

        public static bool IsUrl(string url)
        {
            var regx = new Regex(RegexResource.Url);
            var isRegex = regx.IsMatch(url);
            return isRegex;
        }

        public static string BestUrl(string url)
        {
            var indexChar = url.IndexOf('?');
            if (indexChar != -1)
            {
                url = url.Substring(0, indexChar);
            }
            return url;
        }
    }
}
